package com.lidx.back.statistics.controller.admin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.lidx.back.statistics.entity.SysUser;
import com.lidx.back.statistics.utils.UserUtils;

@Controller
public class LoginController {

	
	@RequestMapping(value={"/admin/index.html","/admin/index","/admin"},method=RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView maView = new ModelAndView("admin/index");
		return maView;
	}
	
	/**
	 * 管理登录
	 */
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
		/*User user = UserUtils.getUser();
		// 如果已经登录，则跳转到管理首页
		if(user.getId() != null){
			return "redirect:"+Global.getAdminPath();
		}*/
		return "login";
	}
	
	/**
	 * 登录失败，真正登录的POST请求由Filter完成
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String loginGo(@RequestParam(value=FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String loginName,
			@RequestParam(required=true) String password,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		SysUser user = UserUtils.getUser();
		// 如果已经登录，则跳转到管理首页
		if(user.getId() != null){
			return "redirect:/admin";
		}
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, loginName);
		//model.addAttribute("isValidateCodeLogin", isValidateCodeLogin(loginName, true, false));
		
		return "redirect:/login";
	}
	
	/**
	 * 退出系统
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "logout")
	public ModelAndView logout(HttpServletRequest request) {
		/*HttpSession session = request.getSession();
		session.invalidate();*/
		Subject subject = SecurityUtils.getSubject();
		if(subject.isAuthenticated()){
			subject.logout();
		}
		ModelAndView modelAndView = new ModelAndView("redirect:/login");
		return modelAndView;
	}
	
	@RequestMapping(value="unauthorized.html")
	public String unauthorized(){
		return "security/unauthorized";
	}
}
